package handler

import (
	"github.com/APP/internal/models"
	"github.com/APP/internal/service/system_service"
	code "github.com/APP/pkg/response"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

type RouteHandler struct {
	routeService system_service.RouteService
}

func NewRouteHandler() *RouteHandler {
	return &RouteHandler{
		routeService: system_service.RouteService{},
	}
}

// CreateRouteRequest 创建路由请求结构
type CreateRouteRequest struct {
	ParentID       *int   `json:"parent_id"`
	Type           int    `json:"type" binding:"required,min=0,max=4"`
	Name           string `json:"name" binding:"required"`
	Title          string `json:"title" binding:"required"`
	Icon           string `json:"icon"`
	ActiveIcon     string `json:"active_icon"`
	Perms          string `json:"perms"`
	Status         int    `json:"status"`
	Path           string `json:"path"`
	ActivePath     string `json:"active_path"`
	Component      string `json:"component"`
	LinkURL        string `json:"link_url"`
	BadgeType      string `json:"badge_type"`
	BadgeContent   string `json:"badge_content"`
	BadgeStyle     string `json:"badge_style"`
	HideMenu       int    `json:"hide_menu"`
	HideChildren   int    `json:"hide_children"`
	HideBreadcrumb int    `json:"hide_breadcrumb"`
	HideTab        int    `json:"hide_tab"`
	KeepAlive      int    `json:"keep_alive"`
	Affix          int    `json:"affix"`
	Sort           int    `json:"sort"`
}

// UpdateRouteRequest 更新路由请求结构
type UpdateRouteRequest struct {
	ParentID       *int   `json:"parent_id"`
	Type           int    `json:"type" binding:"required,min=0,max=4"`
	Name           string `json:"name" binding:"required"`
	Title          string `json:"title" binding:"required"`
	Icon           string `json:"icon"`
	ActiveIcon     string `json:"active_icon"`
	Perms          string `json:"perms"`
	Status         int    `json:"status"`
	Path           string `json:"path"`
	ActivePath     string `json:"active_path"`
	Component      string `json:"component"`
	LinkURL        string `json:"link_url"`
	BadgeType      string `json:"badge_type"`
	BadgeContent   string `json:"badge_content"`
	BadgeStyle     string `json:"badge_style"`
	HideMenu       int    `json:"hide_menu"`
	HideChildren   int    `json:"hide_children"`
	HideBreadcrumb int    `json:"hide_breadcrumb"`
	HideTab        int    `json:"hide_tab"`
	KeepAlive      int    `json:"keep_alive"`
	Affix          int    `json:"affix"`
	Sort           int    `json:"sort"`
}

// RouteListRequest 路由列表请求结构
type RouteListRequest struct {
	Page     int    `form:"page" binding:"min=1"`
	PageSize int    `form:"page_size" binding:"min=1,max=100"`
	Name     string `form:"name"`
	Title    string `form:"title"`
	Type     *int   `form:"type"`
	Status   *int   `form:"status"`
}

// CreateRoute 创建路由
func (h *RouteHandler) CreateRoute(c *gin.Context) {
	var req CreateRouteRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	route := &models.SysRoute{
		ParentID:       req.ParentID,
		Type:           req.Type,
		Name:           req.Name,
		Title:          req.Title,
		Icon:           req.Icon,
		ActiveIcon:     req.ActiveIcon,
		Perms:          req.Perms,
		Status:         req.Status,
		Path:           req.Path,
		ActivePath:     req.ActivePath,
		Component:      req.Component,
		LinkURL:        req.LinkURL,
		BadgeType:      req.BadgeType,
		BadgeContent:   req.BadgeContent,
		BadgeStyle:     req.BadgeStyle,
		HideMenu:       req.HideMenu,
		HideChildren:   req.HideChildren,
		HideBreadcrumb: req.HideBreadcrumb,
		HideTab:        req.HideTab,
		KeepAlive:      req.KeepAlive,
		Affix:          req.Affix,
		Sort:           req.Sort,
		CreatedAt:      time.Now(),
		UpdatedAt:      time.Now(),
	}

	if req.Status == 0 {
		route.Status = 1 // 默认启用
	}

	createdRoute, err := h.routeService.CreateRoute(route)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}

	code.Respond(c, code.Success, createdRoute)
}

// UpdateRoute 更新路由
func (h *RouteHandler) UpdateRoute(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	var req UpdateRouteRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	route := &models.SysRoute{
		ID:             id,
		ParentID:       req.ParentID,
		Type:           req.Type,
		Name:           req.Name,
		Title:          req.Title,
		Icon:           req.Icon,
		ActiveIcon:     req.ActiveIcon,
		Perms:          req.Perms,
		Status:         req.Status,
		Path:           req.Path,
		ActivePath:     req.ActivePath,
		Component:      req.Component,
		LinkURL:        req.LinkURL,
		BadgeType:      req.BadgeType,
		BadgeContent:   req.BadgeContent,
		BadgeStyle:     req.BadgeStyle,
		HideMenu:       req.HideMenu,
		HideChildren:   req.HideChildren,
		HideBreadcrumb: req.HideBreadcrumb,
		HideTab:        req.HideTab,
		KeepAlive:      req.KeepAlive,
		Affix:          req.Affix,
		Sort:           req.Sort,
		UpdatedAt:      time.Now(),
	}

	updatedRoute, err := h.routeService.UpdateRoute(route)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, updatedRoute)
}

// DeleteRoute 删除路由
func (h *RouteHandler) DeleteRoute(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	err = h.routeService.DeleteRoute(id)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, idStr)
}

// GetRoute 获取路由详情
func (h *RouteHandler) GetRoute(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	route, err := h.routeService.GetRoute(id)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, route)
}

// GetRouteList 获取路由列表
func (h *RouteHandler) GetRouteList(c *gin.Context) {
	var req RouteListRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		code.Respond(c, code.ParamError, nil)
		return
	}

	// 设置默认值
	if req.Page == 0 {
		req.Page = 1
	}
	if req.PageSize == 0 {
		req.PageSize = 10
	}

	routes, total, err := h.routeService.GetRouteList(req.Page, req.PageSize, req.Name, req.Title, req.Type, req.Status)
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}

	result := gin.H{
		"list":      routes,
		"total":     total,
		"page":      req.Page,
		"page_size": req.PageSize,
	}
	code.Respond(c, code.Success, result)
}

// GetRouteTree 获取路由树形结构
func (h *RouteHandler) GetRouteTree(c *gin.Context) {
	routes, err := h.routeService.GetRouteTree()
	if err != nil {
		code.Respond(c, code.ServerError.WithError(err), nil)
		return
	}
	code.Respond(c, code.Success, routes)
}
